package org.cuatrovientos.erp.dao;
/**
 * 
 */


import java.util.List;

import org.cuatrovientos.erp.model.Payroll;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author eneko_lana
 *
 */
/**
 * implementation of PayrollDAOInterface
 * @author VB
 *
 */
public class PayrollDAO implements PayrollDAOInterface {

	@Autowired
	 private SessionFactory sessionFactory;
	

	/**
	 * default constructor
	 */
	public PayrollDAO () {
		
	}
	
	/**
	 * returns Hibernate session
	 * @return
	 */
	 private Session getSession () {
		 return sessionFactory.getCurrentSession();
	 }
	
	/* 
	 * selects one Payroll by Id
	 * @param id
	 * @return Payroll
	 */
	 @Transactional(readOnly = true)
	public Payroll selectById(int id) {
		 Payroll Payroll = (Payroll) getSession().get(Payroll.class, id);
	    return Payroll;
	}

	/*
	 * retrieves all Payrolls from db
	 * @return List of Payrolls
	 */
	 @Transactional(readOnly = true)
	 public List<Payroll> selectAll() {
	 
	    List<Payroll> Payrolls = getSession().createQuery("from payroll").list();
	    return Payrolls;
	}
	
	/*
	 * retrieves all Payrolls from db
	 * @return List of Payrolls
	 */
	 @Transactional(readOnly = true)
	public int selectAllCount() {
	    List<Payroll> Payrolls = getSession().createQuery("from payroll").list();
	    return Payrolls.size();
	}

	/*
	 * inserts a new Payroll in database
	 * retrieves generated id and sets to Payroll instance
	 * @param new product
	 */
	 @Transactional
	public void insert(Payroll Payroll) {
	    Integer id = (Integer) getSession().save(Payroll);
	    Payroll.setId(id);           
	}

	/*
	 * updates Payroll
	 * @param Payroll to update
	 */
	 @Transactional
	public void update(Payroll Payroll) {
		getSession().merge(Payroll);
	}

	/*
	 * delete given Payroll
	 * @param Payroll to delete
	 */
	 @Transactional
	public void delete(Payroll Payroll) {
		getSession().delete(Payroll);
	}

	 @Transactional
	public void saveOrUpdate(Payroll Payroll) {

		getSession().saveOrUpdate(Payroll);
		
	}

	 /**
	  * deletes using id
	  */
	 @Transactional
	public void deleteById(int id) {
		 Payroll Payroll = (Payroll) getSession().load(Payroll.class,id);
		 getSession().delete(Payroll);
	}

	 /**
	  * performs search operation
	  */
	 @Transactional(readOnly = true)
	public List<Payroll> search(String description) {
		   Query query = getSession().createQuery("from payroll s where s.description like :description");
           query.setParameter("description", "%"+description+"%");
           
           List<Payroll> descriptions = query.list();
		
           return descriptions;
	}

}
